package com.weilele.library.websocket

import android.os.CountDownTimer
import com.weilele.mvvm.utils.`object`.NetWorkObj
import com.weilele.mvvm.app
import com.weilele.mvvm.logI
import com.weilele.mvvm.utils.activity.runOnUiThread

internal abstract class BaseWebSocket : IWebSocket {
    companion object {
        private const val MAX_AUTO_CONNECT_TIME = 15_000L
    }

    open var webSocketState = WebSocketState.NoConnect
        set(value) {
            field = value
            onSocketStatusChangeCall?.invoke(value)
            when (value) {
                WebSocketState.Connecting -> {

                }
                WebSocketState.NoConnect -> {
                    timeConnect += 1000
                    autoConnect()
                }
                WebSocketState.Connected -> {
                    timeConnect = 0L
                }
            }
        }

    /**
     * 多少秒后自动连接
     */
    private var timeConnect = 0L

    /**
     * 开始自动连接
     */
    private fun autoConnect() {
        if (isCanAutoConnect()) {
            runOnUiThread {
                object : CountDownTimer(timeConnect, 1000) {
                    override fun onFinish() {
                        connect()
                        logI("webSocket:---->Auto Connect when after $timeConnect")
                    }

                    override fun onTick(millisUntilFinished: Long) {
                    }
                }.start()
            }
        } else {

        }
    }

    protected var onMessageCall: Function1<Any?, Unit>? = null
    protected var onSocketStatusChangeCall: Function1<WebSocketState, Unit>? = null

    override fun setOnReceiveMessageListener(onMessage: (Any?) -> Unit) {
        onMessageCall=onMessage
    }

    override fun setOnConnectListener(onSocketStatusChange: (WebSocketState) -> Unit) {
        onSocketStatusChangeCall=onSocketStatusChange
    }

    /**
     * 是否可以自动连接
     * 没网络或者自动连接次数超过限制则不可以自动连接
     */
    private fun isCanAutoConnect(): Boolean {
        return !(!NetWorkObj.isNetWorkConnect || timeConnect > MAX_AUTO_CONNECT_TIME)
    }

    override fun isConnect(): Boolean {
        return webSocketState == WebSocketState.Connected
    }
}